package com.masu.knows.portal.service.impl;

import com.masu.knows.portal.model.Tag;
import com.masu.knows.portal.mapper.TagMapper;
import com.masu.knows.portal.service.ITagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 沈传尚
 * @since 2021-12-07
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements ITagService {
    @Autowired
    private TagMapper tagMapper;

    // 线程安全 并且是读操作无锁的ArrayList 写操作首先copy一个副本,
    private  List<Tag> tags=new CopyOnWriteArrayList<>();

    private Map<String, Tag> tagsMap=new ConcurrentHashMap<>();

    @Override
    public List<Tag> getTags() {
        if (tags.isEmpty()){
            synchronized (tags){
                if (tags.isEmpty()){
                    List<Tag> tagList = tagMapper.selectList(null);
                    tags.addAll(tagList);
                    for (Tag t : tagList){
                        tagsMap.put(t.getName(),t);
                    }
                }
            }
        }
        return tags;
    }

    @Override
    public Map<String, Tag> tagsMap() {
        if (tags.isEmpty()){
            getTags();
        }
        return tagsMap;
    }
}
